<template>
    <div>
      <div class="collect-top">
        <a class="return-btn" @click="stopCollect"><left-outlined />返回</a>
        <div class="title-style">{{ subjectId }}</div>
        <a-divider type="vertical" />
        <div class="collect-exper-keys">
          <span class="mr13">{{ exper.name || '--' }}</span>
          <div class="exper-key">
            <div class="exper-marks">
              <div
                v-for="k in exper.eventMarkKeyList"
                :key="k.id"
                class="exper-mark view"
                @click="mark(k.id)"
              >
                <span class="mark view">{{ keysFormat(k.keys) }}</span>
                <span class="mark">{{ k.tagName }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="collect-content">
        <div v-for="collectItem in collectList" :key="collectItem.deviceModel" class="collect-item">
          <div class="collect-item-left">
            <div class="collect-item-title">
              <div class="line"></div>
              <span>{{ collectItem.deviveName }}</span>
            </div>
            <div class="collect-item-status">
              <img
                v-if="collectItem.status === 'unloaded' || collectItem.status === 'unconnected'"
                src="../../../assets/images/icon_5.png"
                alt=""
              />
              <img v-else src="../../../assets/images/icon_4.png" alt="" />
              <span>{{ collectItem.statusText }}</span>
            </div>
            <div class="collect-item-opera">
              <a-button
                v-if="collectItem.deviceModel === '70'"
                type="primary"
                class="ant-btn-purple"
                :disabled="collectItem.isStartRecord"
                @click="openImpedance"
              >
                <img class="w26" src="../../../assets/images/icon_8.png" alt="" />
                <span>阻抗</span>
              </a-button>
              <a-button
                v-if="!collectItem.isStartRecord"
                :disabled="collectItem.deviceModel == '70' && collectItem.status != 'eeg'"
                type="primary"
                class="ant-btn-green"
                @click="startRecord(collectItem.deviceModel)"
              >
                <img class="w20" src="../../../assets/images/icon_6.png" alt="" />
                <span>开始记录</span>
              </a-button>
              <a-button v-else type="primary">
                <img
                  class="w22"
                  src="../../../assets/images/icon_7.png"
                  alt=""
                  @click="stopRecord(collectItem.deviceModel)"
                />
                <span>结束记录 </span>
              </a-button>
            </div>
          </div>
          <div class="collect-item-right">
            <div :ref="chartRefs[collectItem.deviceModel]" class="chart"></div>
          </div>
        </div>
      </div>
      <div class="collect-bottom">
        <div class="event-mark-box">
          <span>事件标记</span>
          <div class="event-mark">
            <div class="event-mark-items">
              <div v-for="i in 10" :key="i" class="event-mark-item">
                <div class="event-mark-item-date">00:18:01</div>
                <div class="event-mark-item-line"></div>
                <div class="event-mark-item-line2"></div>
                <div class="event-mark-item-dot"></div>
                <div class="event-mark-item-name">EVE1</div>
              </div>
            </div>
            <div class="event-mark-line"></div>
          </div>
        </div>
        <div class="server-status">
          <img src="../../../assets/images/icon_9.png" alt="" />
          <span> 服务器连接正常 </span>
        </div>
      </div>
      <a-modal
        v-model:open="impedanceVisible"
        title="阻抗"
        centered
        :width="560"
        class="impedance-modal"
        @after_close="closeImpedance"
      >
        <div class="impedance-box">
          <div
            v-for="imp in impedanceList"
            :key="imp.value"
            class="impedance-item"
            :style="{ backgroundColor: imp.color }"
          >
            {{ imp.name }}
          </div>
        </div>
        <template #footer> </template>
      </a-modal>
    </div>
  </template>
  
  <script setup lang="ts" name="Collecting">
  import { LeftOutlined } from '@ant-design/icons-vue'
  import { Status, deviceTypes } from '@renderer/utils/constants'
  import {
    IImpedance,
    IExperiment,
    TImpedanceResponse,
    ICollect,
    TExperimentSingleResponse
  } from 'src/types/interfaces'
  import { Ref, nextTick, onBeforeUnmount, ref } from 'vue'
  
  import * as echarts from 'echarts/core'
  import { LineChart } from 'echarts/charts'
  import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent
  } from 'echarts/components'
  import { CanvasRenderer } from 'echarts/renderers'
  import Logger from '@renderer/utils/logger'
  import { keysFormatFun } from '@renderer/utils'
  
  // 注册必须的组件
  echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    LineChart,
    CanvasRenderer
  ])
  
  const emit = defineEmits(['goStep'])
  
  // 被试id
  const subjectId = ref<string>('')
  // 实验id
  const experimentId = ref<string>('')
  // echartDom元素
  const chartRefs: { [key: string]: Ref<HTMLDivElement | null> } = {}
  // 采集列表
  const collectList = ref<ICollect[]>([])
  // 阻抗展示visible
  const impedanceVisible = ref<boolean>(false)
  // 阻抗列表
  const impedanceList = ref<IImpedance[]>([])
  // 是否开始采集脑电数据
  const isInit = ref<boolean>(false)
  
  let timer: any = null
  
  const m =
    'Fp1,Fpz,Fp2,F7,F3,Fz,F4,F8,FC5,FC1,FC2,FC6,M1,T7,C3,Cz,C4,T8,M2,CP5,CP1,CP2,CP6,P7,P3,Pz,P4,P8,POz,O1,Oz,O2,BIP1,BIP2,BIP3,BIP4,BIP5,BIP6,BIP7,BIP8,BIP9,BIP10,BIP11,BIP12,BIP13,BIP14,BIP15,BIP16,BIP17,BIP18,BIP19,BIP20,BIP21,BIP22,BIP23,BIP24,Trigger,SampleCounter'
  const v = m.split(',')
  for (let i = 0; i < 34; i++) {
    const item: IImpedance = {
      name: v[i],
      value: v[i],
      color: '#423abd'
    }
    impedanceList.value.push(item)
  }
  
  // 实验数据
  const exper = ref<IExperiment>({
    id: ``,
    name: ``,
    eventMarkKeyList: [],
    deviceTypes: [],
    deviceTypeList: []
  })
  
  function handleDeviceType(devTypes: string[]) {
    return deviceTypes.filter((item) => devTypes.includes(item.model))
  }
  
  // 结束采集并且返回
  async function stopCollect() {
    try {
      await window.api.stopCollect()
      emit('goStep', 1)
    } catch (error) {
      Logger.info(error)
    }
  }
  
  // 获取实验数据
  const getExperimentById = async () => {
    try {
      const res: TExperimentSingleResponse = await window.api.getExperimentById(experimentId.value)
      if (res && res.data) {
        const data = {
          ...res.data,
          deviceTypeList: handleDeviceType(res.data.deviceTypes)
        }
        data.deviceTypes.forEach((item) => {
          chartRefs[item] = ref(null)
        })
        exper.value = data
        collectList.value = data.deviceTypeList.map((item) => {
          return {
            // 设备类型
            deviceModel: item.model,
            deviveName: item.name,
            // 是否开始采集
            isStartCollect: false,
            // 是否开始记录
            isStartRecord: false,
            // 采集状态
            status: 'connected',
            statusText: Status.connected
          }
        })
        await nextTick()
        handleEchart()
      }
    } catch (error) {
      console.log(error)
    }
  }
  // 展示标记按键
  const keysFormat = (keys) => {
    return keysFormatFun(keys)
  }
  
  // 关闭阻抗，开始采集脑电数据
  const closeImpedance = async () => {
    try {
      await window.api.startEEGCap()
    } catch (error) {
      console.log(error)
    }
  }
  
  // 获取脑电状态
  const getEEGCapStatus = async () => {
    try {
      const res: TImpedanceResponse = await window.api.getEEGCapStatus()
      const index = collectList.value.findIndex((item) => item.deviceModel === '70')
      Logger.info('同步采集Step2 - api获取脑电状态：', res)
      if (index > -1) {
        console.log(index)
        collectList.value[index].status = res.data
        collectList.value[index].statusText = Status[res.data]
        if (res.data !== 'unloaded' && !isInit.value) {
          try {
            await window.api.startEEGCap()
            isInit.value = true
          } catch (error) {
            console.log(error)
          }
        }
      }
    } catch (error) {
      console.log(error)
    }
  }
  
  // 打开阻抗
  const openImpedance = async () => {
    impedanceVisible.value = true
    try {
      // 开启脑电阻抗采集
      const res = await window.api.startEEGImpedanceCap()
      Logger.info('同步采集Step2 - api开启脑电阻抗采集：', res)
    } catch (error) {
      console.log(error)
    }
  }
  
  // 开始记录
  const startRecord = async (model) => {
    if (model === '70') {
      try {
        // 开始记录脑电
        await window.api.startEEGRecord()
      } catch (error) {
        console.log(error)
      }
    }
  }
  
  // 停止记录
  const stopRecord = async (model) => {
    if (model === '70') {
      // 停止记录脑电数据
      try {
        await window.api.stopEEGRecord()
      } catch (error) {
        console.log(error)
      }
    }
  }
  
  // 处理折线图
  const handleEchart = () => {
    for (const k in chartRefs) {
      console.log(k)
      console.log(chartRefs[k])
      console.log(chartRefs[k].value)
      if (chartRefs[k].value && chartRefs[k].value[0]) {
        const myChart = echarts.init(chartRefs[k].value[0])
        const options = {
          title: {
            text: '折线图示例'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['数据1', '数据2']
          },
          xAxis: {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '数据1',
              type: 'line',
              data: [220, 182, 191, 234, 290, 330, 310]
            },
            {
              name: '数据2',
              type: 'line',
              data: [150, 232, 201, 154, 190, 330, 410]
            }
          ]
        }
        myChart.setOption(options)
      }
    }
  }
  
  // 处理所有设备的状态
  const handleStatus = () => {
    const index = collectList.value.findIndex((item) => item.deviceModel === '70')
    if (index > -1) {
      console.log('处理所有设备的状态')
      console.log(index)
      getEEGCapStatus()
  
      timer = setInterval(() => {
        getEEGCapStatus()
      }, 1000)
    }
  }
  // 打开采集
  const open = async (data) => {
    try {
      console.log(data)
      subjectId.value = data.subjectId
      experimentId.value = data.experimentId
      await getExperimentById()
      const res = await window.api.startCollect({
        subjectId: data.subjectId,
        experimentId: data.experimentId
      })
      Logger.info('同步采集Step2 - 开始采集返回数据：', res)
      if (res && res.data) {
        // 注册全局快捷键
        await window.api.registerGlobalShortcut()
      }
      handleStatus()
    } catch (error) {
      Logger.info('同步采集Step2', error)
    }
  }
  
  const mark = async (id: string) => {
    window.api.mark(id)
  }
  // 在组件即将被卸载之前调用,清除定时器
  onBeforeUnmount(() => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  })
  
  // 暴露open方法
  defineExpose({
    open
  })
  </script>
  
  <style lang="less" scoped>
  @import '@renderer/assets/css/exper.less';
  .collect-top {
    position: absolute;
    left: 0;
    top: 91px;
    overflow: hidden;
    width: 100%;
    background: #fff;
    box-sizing: border-box;
    padding: 0 24px;
    height: 75px;
    z-index: 999;
    .flex();
    .ai-center();
    .ant-divider-vertical {
      width: 2px;
      height: 40px;
      background: #8f90a6;
      margin: 0 12px;
    }
  }
  
  .collect-content {
    margin-top: 82px;
  }
  .collect-exper-keys {
    .flex();
    .ai-center();
    .flex1();
    span {
      text-wrap: nowrap;
      &.mr13 {
        margin-right: 13px;
      }
    }
  }
  .exper-key {
    flex: 1;
    overflow-x: auto;
    // width: 1px;
  }
  .exper-marks {
    flex-wrap: nowrap;
  }
  
  .collect-item {
    .flex();
    border: 1px solid @border-color;
    margin-bottom: 20px;
  }
  .collect-item-left {
    width: 253px;
    height: 344px;
    background: #f8f8fa;
    border-right: 1px solid @border-color;
    box-sizing: border-box;
    padding: 22px 15px;
  }
  .collect-item-right {
    .flex1();
  }
  .collect-item-title {
    .flex();
    .ai-center();
    span {
      font-size: 16px;
      font-weight: bold;
      color: @text-black-color;
      line-height: 22px;
      margin-left: 8px;
    }
  }
  .collect-item-status {
    margin-top: 32px;
    padding-bottom: 5px;
    .flex();
    .ai-center();
    .jc-center();
    img {
      width: 27px;
      height: 27px;
    }
    span {
      margin-left: 4px;
      font-size: 14px;
      font-weight: normal;
      color: @text-black-color;
    }
  }
  .collect-item-opera {
    .ant-btn {
      .flex();
      .ai-center();
      .jc-center();
      width: 142px;
      margin-top: 17px;
      margin: 17px auto 0;
      .h-l(34px);
      img {
        margin-right: 6px;
      }
      img.w20 {
        width: 20px;
        height: 20px;
      }
      img.w26 {
        width: 26px;
        height: 26px;
      }
      img.w22 {
        width: 22px;
        height: 22px;
      }
    }
  }
  .collect-bottom {
    position: relative;
    height: 98px;
    background: #f8f8fa;
  }
  .server-status {
    .flex();
    .ai-center();
    position: absolute;
    left: 0;
    bottom: 0;
    background: rgba(6, 194, 112, 0.14);
    padding: 6px 12px;
    img {
      width: 15px;
      height: 15px;
      border-radius: 2px;
    }
    span {
      margin-left: 3px;
      font-size: 14px;
      font-weight: bold;
      color: @text-black-color;
    }
  }
  .event-mark-box {
    .flex();
    .ai-center();
    span {
      margin-left: 228px;
      margin-right: 22px;
      font-size: @font-16;
      font-weight: bold;
      color: @text-black-color;
      text-wrap: nowrap;
    }
  }
  .event-mark {
    position: relative;
    margin-left: 22px;
    padding: 20px 34px 8px 0;
    .flex1();
    overflow-x: auto;
  }
  .event-mark-items {
    .flex();
    .ai-center();
  }
  .event-mark-line {
    position: absolute;
    left: 0;
    bottom: 34px;
    width: 100%;
    height: 2px;
    background: #3784d6;
    border-radius: 7px;
    z-index: 2;
  }
  .event-mark-item {
    position: relative;
    z-index: 3;
    text-align: center;
    min-width: 66px;
  }
  
  .event-mark-item-date {
    font-size: 13px;
    line-height: 18px;
    font-weight: 400;
    color: #8f90a6;
    padding: 0 10px;
  }
  .event-mark-item-line {
    width: 1px;
    height: 22px;
    border: 1px solid @primary-color;
    margin-top: 6px;
    margin: 0 auto;
  }
  .event-mark-item-line2 {
    width: 100%;
    height: 2px;
    background: #3784d6;
  }
  .event-mark-item-dot {
    width: 16px;
    height: 16px;
    background: #47af4b;
    border-radius: 16px;
    margin: -8px auto;
  }
  .event-mark-item-name {
    font-size: 14px;
    font-weight: 400;
    color: #222222;
    line-height: 14px;
    margin-top: 12px;
  }
  .impedance-box,
  .impedance-item {
    border: 1px solid @border-color;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .impedance-box {
    width: 500px;
    height: 500px;
    border-radius: 500px;
    flex-wrap: wrap;
  }
  .impedance-item {
    width: 50px;
    height: 50px;
    border-radius: 50px;
    margin-right: 10px;
    color: #fff;
  }
  .chart {
    width: 100%;
    height: 344px;
  }
  </style>
  